package com.pine.dcts.auth.verfivation;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author xiaoyuan
 * @create 2020/7/1 14:56
 **/
public class InMemoryVerificationCodeCache implements VerificationCodeCache {

    private final Cache<String, String> cache;
    private Long expireIn = 5L * 60L*1000L;

    public InMemoryVerificationCodeCache() {
        cache = CacheBuilder.newBuilder().expireAfterWrite(expireIn, TimeUnit.MILLISECONDS).build();
    }

    public InMemoryVerificationCodeCache(Long expireIn) {
        this.expireIn = expireIn;
        cache = CacheBuilder.newBuilder().expireAfterWrite(expireIn, TimeUnit.MILLISECONDS).build();
    }
    @Override
    public void set(String cacheName, String key, String value) {
        cache.put(cacheName + ":" + key, value);
    }

    @Override
    public void remove(String cacheName, String key) {
        cache.invalidate(cacheName + ":" + key);
    }

    @Override
    public String get(String cacheName, String key) {
        return cache.getIfPresent(cacheName + ":" + key);
    }

    @Override
    public boolean validate(String cacheName, String key, String value) {
        String originValue = this.get(cacheName,key);
        //remove(cacheName,key);//获取后去除
        if(StringUtils.isNotEmpty(originValue)){
            return originValue.equalsIgnoreCase(value);
        }
        return  false;
    }

    @Override
    public boolean isExpire(String cacheName, String key) {
        return  get(cacheName,key)==null;
    }
}
